import dao.BaseDao;
import dao.TicketDao;
import dao.TrainDao;
import dao.UserDao;
import service.TicketService;
import service.TrainService;
import service.UserService;
import model.Ticket;
import model.Train;
import model.User;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * Mini-12306 铁路票务系统主程序
 */
public class MainGUI extends JFrame {
    private static User currentUser = null;
    private static UserService userService = new UserService();
    private static TrainService trainService = new TrainService();
    private static TicketService ticketService = new TicketService();

    private CardLayout cardLayout;
    private JPanel mainPanel;
    private JList<String> navList;
    private DefaultListModel<String> navListModel;
    private JPanel contentPanel;
    private JLabel welcomeLabel;

    // 颜色常量
    private static final Color PRIMARY_COLOR = new Color(60, 152, 251);
    private static final Color SECONDARY_COLOR = new Color(241, 243, 244);
    private static final Color ACCENT_COLOR = new Color(255, 102, 0);
    private static final Color TEXT_COLOR = new Color(32, 33, 36);
    private static final Color LIGHT_TEXT_COLOR = new Color(95, 99, 104);

    public MainGUI() {
        // 设置 Nimbus 外观以获得更好的视觉效果
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    // 自定义 Nimbus 颜色
                    UIManager.put("nimbusBase", new Color(240, 240, 240));
                    UIManager.put("nimbusBlueGrey", new Color(200, 200, 200));
                    UIManager.put("control", new Color(240, 240, 240));
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 初始化数据库
        BaseDao.initDatabase();

        // 设置窗口属性
        setTitle("Mini-12306 铁路票务系统");
        setSize(1100, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 使用内容根路径加载应用程序图标
        try {
            // 假设图片位于项目根目录下的resources文件夹中
            File iconFile = new File("resources/train_icon.png");
            if (iconFile.exists()) {
                URL iconUrl = iconFile.toURI().toURL();
                setIconImage(new ImageIcon(iconUrl).getImage());
            } else {
                System.err.println("警告: 找不到应用程序图标文件");
            }
        } catch (MalformedURLException e) {
            System.err.println("警告: 加载应用程序图标时发生错误: " + e.getMessage());
        }
        // 创建主面板和布局管理器
        mainPanel = new JPanel(new BorderLayout());
        // 初始化登录界面
        mainPanel.add(createLoginScreen(), BorderLayout.CENTER);
        // 将主面板添加到窗口
        add(mainPanel);
    }

    // 创建登录界面
    private JPanel createLoginScreen() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(Color.WHITE);

        // 创建左侧图片面板
        JPanel imagePanel = new JPanel();
        imagePanel.setBackground(PRIMARY_COLOR);
        imagePanel.setPreferredSize(new Dimension(400, 0));

        // 尝试加载登录背景图，使用内容根路径
        try {
            // 假设图片位于项目根目录下的resources文件夹中
            File backgroundFile = new File("resources/train_background.png");
            if (backgroundFile.exists()) {
                URL backgroundUrl = backgroundFile.toURI().toURL();
                JLabel imageLabel = new JLabel(new ImageIcon(backgroundUrl));
                imagePanel.add(imageLabel);
            } else {
                System.err.println("警告: 找不到登录背景图像文件");
                // 添加一个默认的文本标签替代图像
                JLabel placeholderLabel = new JLabel("铁路票务系统");
                placeholderLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
                placeholderLabel.setForeground(Color.WHITE);
                imagePanel.add(placeholderLabel);
            }
        } catch (MalformedURLException e) {
            System.err.println("警告: 加载登录背景图像时发生错误: " + e.getMessage());
        }

        // 创建右侧登录表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBackground(Color.WHITE);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 20, 10, 20);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 标题
        JLabel titleLabel = new JLabel("欢迎使用 Mini-12306");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(PRIMARY_COLOR);
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(20, 20, 40, 20);
        formPanel.add(titleLabel, gbc);

        // 用户名
        JLabel usernameLabel = new JLabel("用户名:");
        usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.LINE_START;
        gbc.insets = new Insets(10, 20, 5, 20);
        formPanel.add(usernameLabel, gbc);

        JTextField usernameField = new JTextField(20);
        usernameField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        usernameField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                new EmptyBorder(5, 10, 5, 10)
        ));
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.insets = new Insets(0, 20, 10, 20);
        formPanel.add(usernameField, gbc);

        // 密码
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.insets = new Insets(10, 20, 5, 20);
        formPanel.add(passwordLabel, gbc);

        JPasswordField passwordField = new JPasswordField(20);
        passwordField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        passwordField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                new EmptyBorder(5, 10, 5, 10)
        ));
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.insets = new Insets(0, 20, 30, 20);
        formPanel.add(passwordField, gbc);

        // 登录按钮
        JButton loginButton = new JButton("登录");
        loginButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        loginButton.setBackground(PRIMARY_COLOR);
        loginButton.setForeground(Color.WHITE);
        loginButton.setFocusPainted(false);
        loginButton.setBorder(new EmptyBorder(10, 20, 10, 20));
        loginButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        loginButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                loginButton.setBackground(new Color(21, 95, 192));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                loginButton.setBackground(PRIMARY_COLOR);
            }
        });

        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.insets = new Insets(10, 20, 10, 20);
        formPanel.add(loginButton, gbc);

        // 注册按钮
        JButton registerButton = new JButton("注册");
        registerButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        registerButton.setForeground(PRIMARY_COLOR);
        registerButton.setContentAreaFilled(false);
        registerButton.setFocusPainted(false);
        registerButton.setBorder(new EmptyBorder(5, 10, 5, 10));
        registerButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        registerButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                registerButton.setForeground(new Color(21, 95, 192));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                registerButton.setForeground(PRIMARY_COLOR);
            }
        });

        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.insets = new Insets(5, 20, 20, 20);
        formPanel.add(registerButton, gbc);

        // 登录按钮事件处理
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());
                User user = userService.login(username, password);
                if (user != null) {
                    currentUser = user;
                    // 切换到主界面
                    mainPanel.removeAll();
                    mainPanel.add(createMainInterface(), BorderLayout.CENTER);
                    mainPanel.revalidate();
                    mainPanel.repaint();

                    // 更新欢迎信息
                    welcomeLabel.setText("欢迎回来，" + currentUser.getName() + "！");

                    // 根据用户角色设置导航项
                    setupNavigationItems();

                    JOptionPane.showMessageDialog(null, "登录成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "用户名或密码错误。", "登录失败", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 注册按钮事件处理
        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String account = JOptionPane.showInputDialog("请输入用户名:");
                if (account == null) return;
                String password = JOptionPane.showInputDialog("请输入密码:");
                if (password == null) return;
                String name = JOptionPane.showInputDialog("请输入姓名:");
                if (name == null) return;
                String idCardNo = "";
                while (true) {
                    idCardNo = JOptionPane.showInputDialog("请输入身份证号:");
                    if (idCardNo == null) return;
                    if (isValidIdCardNo(idCardNo)) {
                        break;
                    }
                    JOptionPane.showMessageDialog(null, "身份证号格式错误，请输入 18 位身份证号。");
                }
                String mobileNo = "";
                while (true) {
                    mobileNo = JOptionPane.showInputDialog("请输入手机号:");
                    if (mobileNo == null) return;
                    if (isValidMobileNo(mobileNo)) {
                        break;
                    }
                    JOptionPane.showMessageDialog(null, "手机号格式错误，请输入 11 位且以 1 开头的手机号。");
                }
                String bankCardNo = "";
                while (true) {
                    bankCardNo = JOptionPane.showInputDialog("请输入银行卡号:");
                    if (bankCardNo == null) return;
                    if (isValidBankCardNo(bankCardNo)) {
                        break;
                    }
                    JOptionPane.showMessageDialog(null, "银行卡号格式错误，请输入 19 位银行卡号。");
                }
                String ageStr = JOptionPane.showInputDialog("请输入年龄:");
                if (ageStr == null) return;
                int age = Integer.parseInt(ageStr);

                User user = new User(account, password, name, idCardNo, mobileNo, bankCardNo, false, age);
                if (userService.register(user)) {
                    JOptionPane.showMessageDialog(null, "注册成功！请登录。", "注册成功", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "注册失败，用户名可能已存在。请重新输入。", "注册失败", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 添加到主面板
        panel.add(imagePanel, BorderLayout.WEST);
        panel.add(formPanel, BorderLayout.CENTER);

        return panel;
    }

    // 创建主界面
    private JPanel createMainInterface() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建顶部导航栏
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(PRIMARY_COLOR);
        topPanel.setPreferredSize(new Dimension(0, 60));

        // 左侧标题
        JLabel titleLabel = new JLabel("Mini-12306 铁路票务系统");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setBorder(new EmptyBorder(0, 20, 0, 0));
        topPanel.add(titleLabel, BorderLayout.WEST);

        // 右侧欢迎信息和退出按钮
        JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        rightPanel.setBackground(PRIMARY_COLOR);

        welcomeLabel = new JLabel("欢迎回来，用户！");
        welcomeLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        welcomeLabel.setForeground(Color.WHITE);
        welcomeLabel.setBorder(new EmptyBorder(0, 0, 0, 20));
        rightPanel.add(welcomeLabel);

        JButton logoutButton = new JButton("退出登录");
        logoutButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        logoutButton.setBackground(new Color(21, 95, 192));
        logoutButton.setForeground(Color.WHITE);
        logoutButton.setFocusPainted(false);
        logoutButton.setBorder(new EmptyBorder(5, 15, 5, 15));
        logoutButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        logoutButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                logoutButton.setBackground(new Color(16, 80, 160));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                logoutButton.setBackground(new Color(21, 95, 192));
            }
        });

        logoutButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int confirm = JOptionPane.showConfirmDialog(null, "确定要退出登录吗？", "确认退出", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    currentUser = null;
                    mainPanel.removeAll();
                    mainPanel.add(createLoginScreen(), BorderLayout.CENTER);
                    mainPanel.revalidate();
                    mainPanel.repaint();
                    JOptionPane.showMessageDialog(null, "已退出登录。", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });

        rightPanel.add(logoutButton);
        topPanel.add(rightPanel, BorderLayout.EAST);

        panel.add(topPanel, BorderLayout.NORTH);

        // 创建主内容区域
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setDividerLocation(200);
        splitPane.setDividerSize(1);

        // 左侧导航面板
        JPanel navPanel = new JPanel(new BorderLayout());
        navPanel.setBackground(SECONDARY_COLOR);

        navListModel = new DefaultListModel<>();
        navList = new JList<>(navListModel);
        navList.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        navList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        navList.setCellRenderer(new NavListCellRenderer());
        navList.setBorder(new EmptyBorder(10, 0, 0, 0));
        navList.setBackground(SECONDARY_COLOR);


        // 导航项选择事件
        navList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    String selectedItem = navList.getSelectedValue();
                    if (selectedItem != null) {
                        showContentPanel(selectedItem);
                    }
                }
            }
        });

        JScrollPane navScrollPane = new JScrollPane(navList);
        navScrollPane.setBorder(null);
        navPanel.add(navScrollPane, BorderLayout.CENTER);

        splitPane.setLeftComponent(navPanel);

        // 右侧内容面板
        cardLayout = new CardLayout();
        contentPanel = new JPanel(cardLayout);
        contentPanel.setBackground(Color.WHITE);

        splitPane.setRightComponent(contentPanel);

        panel.add(splitPane, BorderLayout.CENTER);

        return panel;
    }



    // 设置导航项
    private void setupNavigationItems() {
        navListModel.clear();

        if (currentUser.isAdmin()) {
            // 管理员导航项
            navListModel.addElement("添加列车");
            navListModel.addElement("查看所有列车");
            navListModel.addElement("查看所有车票");
        } else {
            // 普通用户导航项
            navListModel.addElement("查询列车");
            navListModel.addElement("购票");
            navListModel.addElement("我的车票");
            navListModel.addElement("退票");
        }
        // 默认选择第一个导航项
        if (navListModel.size() > 0) {
            navList.setSelectedIndex(0);
        }
        navList.setModel(navListModel);
    }


    // 显示内容面板
    private void showContentPanel(String panelName) {
        // 检查面板是否已存在
        Component[] components = contentPanel.getComponents();
        for (Component component : components) {
            if (component.getName() != null && component.getName().equals(panelName)) {
                cardLayout.show(contentPanel, panelName);
                return;
            }
        }

        // 如果面板不存在，创建新面板
        JPanel panel = null;

        if (panelName.equals("查询列车")) {
            panel = createSearchTrainPanel();
        } else if (panelName.equals("购票")) {
            panel = createBookTicketPanel();
        } else if (panelName.equals("我的车票")) {
            panel = createMyTicketsPanel();
        } else if (panelName.equals("退票")) {
            panel = createCancelTicketPanel();
        } else if (panelName.equals("添加列车")) {
            panel = createAddTrainPanel();
        } else if (panelName.equals("查看所有列车")) {
            panel = createViewAllTrainsPanel();
        } else if (panelName.equals("查看所有车票")) {  // 新增车票展示面板
            panel = createViewAllTicketsPanel();
        }

        if (panel != null) {
            panel.setName(panelName);
            contentPanel.add(panel, panelName);
            cardLayout.show(contentPanel, panelName);
        }
    }

    //  创建查看所有车票面板
    private JPanel createViewAllTicketsPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("所有车票记录");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(TEXT_COLOR);
        panel.add(titleLabel, BorderLayout.NORTH);

        // 车票表格
        String[] columnNames = {"票号", "用户", "车次", "座位号", "票价", "状态", "购买时间"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable ticketTable = new JTable(tableModel);
        ticketTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        ticketTable.setRowHeight(30);
        ticketTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
        ticketTable.getTableHeader().setBackground(new Color(240, 240, 240));

        JScrollPane tableScrollPane = new JScrollPane(ticketTable);
        panel.add(tableScrollPane, BorderLayout.CENTER);

        // 刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        refreshButton.setBackground(PRIMARY_COLOR);
        refreshButton.setForeground(Color.WHITE);
        refreshButton.setFocusPainted(false);
        refreshButton.setBorder(new EmptyBorder(8, 20, 8, 20));
        refreshButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 悬停效果
        refreshButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                refreshButton.setBackground(new Color(21, 95, 192));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                refreshButton.setBackground(PRIMARY_COLOR);
            }
        });

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBorder(new EmptyBorder(10, 0, 0, 0));
        buttonPanel.add(refreshButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 刷新数据
        ActionListener refreshAction = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                tableModel.setRowCount(0); // 清空表格

                List<Ticket> tickets = ticketService.getAllTickets();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

                for (Ticket ticket : tickets) {
                    User user = userService.getUserById(ticket.getUserId());
                    Train train = trainService.getTrainById(ticket.getTrainId());

                    Object[] row = {
                            ticket.getId(),
                            user != null ? user.getName() : "未知用户",
                            train != null ? train.getTrainNumber() : "未知车次",
                            ticket.getSeatNumber(),
                            ticket.getPrice(),
                            ticket.isCancelled() ? "已退票" : "已购买",
                            dateFormat.format(ticket.getBookingTime())
                    };
                    tableModel.addRow(row);
                }
            }
        };

        // 初始加载数据
        refreshAction.actionPerformed(null);
        // 绑定按钮事件
        refreshButton.addActionListener(refreshAction);

        return panel;
    }

    // 创建查询列车面板
    private JPanel createSearchTrainPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("查询列车");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(TEXT_COLOR);
        titleLabel.setBorder(new EmptyBorder(0, 0, 10, 0));
        panel.add(titleLabel, BorderLayout.NORTH);

        // 查询表单
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                new EmptyBorder(20, 20, 20, 20)
        ));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 10, 5, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 出发地
        JLabel departureLabel = new JLabel("出发地:");
        departureLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.LINE_START;
        formPanel.add(departureLabel, gbc);

        JTextField departureField = new JTextField(15);
        departureField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 0;
        formPanel.add(departureField, gbc);

        // 目的地
        JLabel destinationLabel = new JLabel("目的地:");
        destinationLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(destinationLabel, gbc);

        JTextField destinationField = new JTextField(15);
        destinationField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 1;
        formPanel.add(destinationField, gbc);

        // 出发日期
        JLabel dateLabel = new JLabel("出发日期:");
        dateLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(dateLabel, gbc);

        JTextField dateField = new JTextField(15);
        dateField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        dateField.setToolTipText("格式: YYYY-MM-DD");
        gbc.gridx = 1;
        gbc.gridy = 2;
        formPanel.add(dateField, gbc);

        // 查询按钮
        JButton searchButton = new JButton("查询");
        searchButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        searchButton.setBackground(PRIMARY_COLOR);
        searchButton.setForeground(Color.WHITE);
        searchButton.setFocusPainted(false);
        searchButton.setBorder(new EmptyBorder(8, 20, 8, 20));
        searchButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        searchButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                searchButton.setBackground(new Color(21, 95, 192));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                searchButton.setBackground(PRIMARY_COLOR);
            }
        });

        gbc.gridx = 1;
        gbc.gridy = 3;
        gbc.insets = new Insets(15, 10, 5, 10);
        formPanel.add(searchButton, gbc);

        panel.add(formPanel, BorderLayout.NORTH);

        // 结果表格
        String[] columnNames = {"ID", "车次", "出发站", "到达站", "出发时间", "到达时间", "票价", "余票"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable resultTable = new JTable(tableModel);
        resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        resultTable.setRowHeight(30);
        resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
        resultTable.getTableHeader().setBackground(new Color(240, 240, 240));
        resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JScrollPane tableScrollPane = new JScrollPane(resultTable);
        tableScrollPane.setBorder(new EmptyBorder(20, 0, 0, 0));
        panel.add(tableScrollPane, BorderLayout.CENTER);

        // 查询按钮事件处理
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String departure = departureField.getText();
                String destination = destinationField.getText();
                String dateStr = dateField.getText();

                if (departure.isEmpty() || destination.isEmpty() || dateStr.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "请填写完整的查询信息！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                Date date = null;
                try {
                    date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
                } catch (ParseException ex) {
                    JOptionPane.showMessageDialog(null, "日期格式错误，请使用 YYYY-MM-DD 格式！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                List<Train> trains = trainService.searchTrains(departure, destination, date);

                // 清空表格
                tableModel.setRowCount(0);

                if (trains.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "没有找到符合条件的列车。", "查询结果", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    // 添加结果到表格
                    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
                    for (Train train : trains) {
                        Object[] row = {
                                train.getId(),
                                train.getTrainNumber(),
                                train.getDeparture(),
                                train.getDestination(),
                                timeFormat.format(train.getDepartureTime()),
                                timeFormat.format(train.getArrivalTime()),
                                train.getPrice(),
                                train.getAvailableSeats()
                        };
                        tableModel.addRow(row);
                    }
                }
            }
        });

        return panel;
    }

    // 创建购票面板
    private JPanel createBookTicketPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("购票");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(TEXT_COLOR);
        titleLabel.setBorder(new EmptyBorder(0, 0, 10, 0));
        panel.add(titleLabel, BorderLayout.NORTH);

        // 查询表单
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                new EmptyBorder(20, 20, 20, 20)
        ));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 10, 5, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 出发地
        JLabel departureLabel = new JLabel("出发地:");
        departureLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.LINE_START;
        formPanel.add(departureLabel, gbc);

        JTextField departureField = new JTextField(15);
        departureField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 0;
        formPanel.add(departureField, gbc);

        // 目的地
        JLabel destinationLabel = new JLabel("目的地:");
        destinationLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(destinationLabel, gbc);

        JTextField destinationField = new JTextField(15);
        destinationField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 1;
        formPanel.add(destinationField, gbc);

        // 出发日期
        JLabel dateLabel = new JLabel("出发日期:");
        dateLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(dateLabel, gbc);

        JTextField dateField = new JTextField(15);
        dateField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        dateField.setToolTipText("格式: YYYY-MM-DD");
        gbc.gridx = 1;
        gbc.gridy = 2;
        formPanel.add(dateField, gbc);

        // 查询按钮
        JButton searchButton = new JButton("查询列车");
        searchButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        searchButton.setBackground(PRIMARY_COLOR);
        searchButton.setForeground(Color.WHITE);
        searchButton.setFocusPainted(false);
        searchButton.setBorder(new EmptyBorder(8, 20, 8, 20));
        searchButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        searchButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                searchButton.setBackground(new Color(21, 95, 192));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                searchButton.setBackground(PRIMARY_COLOR);
            }
        });

        gbc.gridx = 1;
        gbc.gridy = 3;
        gbc.insets = new Insets(15, 10, 5, 10);
        formPanel.add(searchButton, gbc);

        panel.add(formPanel, BorderLayout.NORTH);

        // 结果表格
        String[] columnNames = {"ID", "车次", "出发站", "到达站", "出发时间", "到达时间", "票价", "余票", "操作"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 8; // 只有最后一列可编辑
            }
        };
        JTable resultTable = new JTable(tableModel);
        resultTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        resultTable.setRowHeight(30);
        resultTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
        resultTable.getTableHeader().setBackground(new Color(240, 240, 240));
        resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 设置操作列的渲染器和编辑器
        TableCellRenderer buttonRenderer = (TableCellRenderer) new JButtonRenderer();
        resultTable.getColumnModel().getColumn(8).setCellRenderer(buttonRenderer);
        resultTable.getColumnModel().getColumn(8).setCellEditor(
                new DefaultCellEditor(new JCheckBox()) {
                    private JButton button = new JButton("购票");

                    @Override
                    public Component getTableCellEditorComponent(JTable table, Object value,
                                                                 boolean isSelected, int row, int column) {
                        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
                        button.setBackground(ACCENT_COLOR);
                        button.setForeground(Color.WHITE);
                        button.setFocusPainted(false);
                        button.setBorder(new EmptyBorder(5, 10, 5, 10));

                        // 获取列车ID
                        int trainId = (int) table.getValueAt(row, 0);
                        Train train = trainService.getTrainById(trainId);

                        button.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                // 创建选择车厢和座位的对话框
                                JDialog seatDialog = new JDialog();
                                seatDialog.setTitle("选择座位");
                                seatDialog.setSize(400, 300);
                                seatDialog.setLayout(new BorderLayout());
                                seatDialog.setLocationRelativeTo(null);
                                seatDialog.setModal(true);

                                // 车厢选择面板
                                JPanel carriagePanel = new JPanel(new FlowLayout());
                                JLabel carriageLabel = new JLabel("选择车厢:");
                                carriagePanel.add(carriageLabel);

                                // 获取可用车厢
                                String[] carriages = train.getCarriages();
                                int[] carriageSeats = train.getCarriageSeats();
                                JComboBox<String> carriageCombo = new JComboBox<>();

                                // 只添加有座位的车厢
                                for (int i = 0; i < carriages.length; i++) {
                                    if (carriageSeats[i] > 0) {
                                        carriageCombo.addItem(carriages[i] + "车厢 (余票: " + carriageSeats[i] + ")");
                                    }
                                }
                                carriagePanel.add(carriageCombo);
                                seatDialog.add(carriagePanel, BorderLayout.NORTH);

                                // 座位选择面板
                                JPanel seatPanel = new JPanel(new GridLayout(0, 5, 5, 5));
                                seatPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
                                JScrollPane seatScrollPane = new JScrollPane(seatPanel);
                                seatDialog.add(seatScrollPane, BorderLayout.CENTER);

                                // 监听车厢选择变化
                                carriageCombo.addActionListener(new ActionListener() {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        seatPanel.removeAll();

                                        // 获取选中的车厢索引
                                        String selected = (String) carriageCombo.getSelectedItem();
                                        String carriage = selected.substring(0, 1); // 获取车厢字母
                                        int carriageIndex = -1;
                                        for (int i = 0; i < carriages.length; i++) {
                                            if (carriages[i].equals(carriage)) {
                                                carriageIndex = i;
                                                break;
                                            }
                                        }

                                        if (carriageIndex != -1) {
                                            // 创建该车厢的座位按钮
                                            int seats = carriageSeats[carriageIndex];
                                            for (int i = 1; i <= seats; i++) {
                                                JButton seatButton = new JButton(String.valueOf(i));
                                                seatButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
                                                seatButton.setBackground(Color.WHITE);
                                                seatButton.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));

                                                seatButton.addActionListener(new ActionListener() {
                                                    @Override
                                                    public void actionPerformed(ActionEvent e) {
// 处理座位选择
                                                        String seatStr = carriage + "车厢 " + seatButton.getText() + "号";
                                                        boolean success = bookTicketWithSeat(currentUser.getId(), trainId, seatStr);

                                                        if (success) {
                                                            // 获取用户的车票信息
                                                            List<Ticket> tickets = ticketService.getUserTickets(currentUser.getId());
                                                            if (!tickets.isEmpty()) {
                                                                Ticket latestTicket = tickets.get(tickets.size() - 1);
                                                                double price = latestTicket.getPrice();
                                                                String ticketType = latestTicket.isStudentTicket() ? "学生票" : "成人票";
                                                                JOptionPane.showMessageDialog(null, "购票成功！已支付 " + price + " 元，购买的是 " + ticketType + "。座位号: " + seatStr, "购票成功", JOptionPane.INFORMATION_MESSAGE);

                                                                // 更新表格中的余票信息
                                                                if (tableModel.getColumnCount() > 7) { // 检查列数是否足够
                                                                    int availableSeats = (int) tableModel.getValueAt(row, 7);
                                                                    tableModel.setValueAt(availableSeats - 1, row, 7);
                                                                }
                                                            } else {
                                                                JOptionPane.showMessageDialog(null, "购票成功！但获取车票信息失败。", "购票成功", JOptionPane.INFORMATION_MESSAGE);
                                                            }
                                                            seatDialog.dispose();
                                                        } else {
                                                            JOptionPane.showMessageDialog(null, "购票失败，可能是列车不存在或已无余票。", "购票失败", JOptionPane.ERROR_MESSAGE);
                                                        }
                                                    }
                                                });

                                                seatPanel.add(seatButton);
                                            }
                                        }

                                        seatPanel.revalidate();
                                        seatPanel.repaint();
                                    }
                                });


                                // 触发一次车厢选择事件以显示初始座位
                                carriageCombo.setSelectedIndex(0);

                                // 添加取消按钮
                                JButton cancelButton = new JButton("取消");
                                cancelButton.addActionListener(new ActionListener() {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        seatDialog.dispose();
                                    }
                                });

                                JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
                                buttonPanel.add(cancelButton);
                                seatDialog.add(buttonPanel, BorderLayout.SOUTH);

                                seatDialog.setVisible(true);
                            }
                        });

                        return button;
                    }

                    @Override
                    public Object getCellEditorValue() {
                        return null;
                    }
                }
        );

        JScrollPane tableScrollPane = new JScrollPane(resultTable);
        tableScrollPane.setBorder(new EmptyBorder(20, 0, 0, 0));
        panel.add(tableScrollPane, BorderLayout.CENTER);

        // 查询按钮事件处理
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String departure = departureField.getText();
                String destination = destinationField.getText();
                String dateStr = dateField.getText();

                if (departure.isEmpty() || destination.isEmpty() || dateStr.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "请填写完整的查询信息！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                Date date = null;
                try {
                    date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
                } catch (ParseException ex) {
                    JOptionPane.showMessageDialog(null, "日期格式错误，请使用 YYYY-MM-DD 格式！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                List<Train> trains = trainService.searchTrains(departure, destination, date);

                // 清空表格
                tableModel.setRowCount(0);

                if (trains.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "没有找到符合条件的列车。", "查询结果", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    // 添加结果到表格
                    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
                    for (Train train : trains) {
                        Object[] row = {
                                train.getId(),
                                train.getTrainNumber(),
                                train.getDeparture(),
                                train.getDestination(),
                                timeFormat.format(train.getDepartureTime()),
                                timeFormat.format(train.getArrivalTime()),
                                train.getPrice(),
                                train.getAvailableSeats(),
                                "购票"
                        };
                        tableModel.addRow(row);
                    }
                }
            }
        });

        return panel;
    }





    // 带座位选择的购票方法
    private boolean bookTicketWithSeat(int userId, int trainId, String seatStr) {
        // 检查列车是否存在
        Train train = TrainDao.getById(trainId);
        if (train == null || train.getAvailableSeats() <= 0) {
            return false;
        }

        // 获取用户信息
        User user = UserDao.getById(userId);
        if (user == null) {
            return false;
        }

        // 计算票价（成人票与学生票）
        double price = train.getPrice();
        boolean isStudentTicket = false;
        if (user.getAge() <= 18) {
            price = price / 2;
            isStudentTicket = true;
        }

        // 解析车厢信息
        String carriage = seatStr.substring(0, 1); // 获取车厢字母
        String[] carriages = train.getCarriages();
        int[] carriageSeats = train.getCarriageSeats();
        int carriageIndex = -1;

        // 查找车厢索引
        for (int i = 0; i < carriages.length; i++) {
            if (carriages[i].equals(carriage)) {
                carriageIndex = i;
                break;
            }
        }

        if (carriageIndex == -1 || carriageSeats[carriageIndex] <= 0) {
            return false; // 无效的车厢或已无座位
        }

        // 创建车票
        Ticket ticket = new Ticket(userId, trainId, seatStr, new Date(), price, isStudentTicket);
        boolean success = TicketDao.addTicket(ticket);

        // 更新列车座位数
        if (success) {
            // 减少对应车厢的座位数
            carriageSeats[carriageIndex]--;
            // 更新车厢座位信息到数据库
            updateCarriageSeats(trainId, carriageSeats);
            // 更新总座位数
            return TrainDao.updateSeats(trainId, train.getAvailableSeats() - 1);
        }
        return false;
    }

    // 更新车厢座位信息到数据库
    private boolean updateCarriageSeats(int trainId, int[] carriageSeats) {
        StringBuilder seatsStr = new StringBuilder();
        for (int i = 0; i < carriageSeats.length; i++) {
            seatsStr.append(carriageSeats[i]);
            if (i < carriageSeats.length - 1) {
                seatsStr.append(",");
            }
        }

        String sql = "UPDATE trains SET 车厢座位信息 = ? WHERE id = ?";
        try (Connection conn = BaseDao.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, seatsStr.toString());
            pstmt.setInt(2, trainId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 创建我的车票面板
    private JPanel createMyTicketsPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("我的车票");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(TEXT_COLOR);
        titleLabel.setBorder(new EmptyBorder(0, 0, 10, 0));
        panel.add(titleLabel, BorderLayout.NORTH);

        // 车票表格
        String[] columnNames = {"票号", "车次", "座位号", "出发站", "到达站", "出发时间", "票价", "票类型"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable ticketTable = new JTable(tableModel);
        ticketTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        ticketTable.setRowHeight(30);
        ticketTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
        ticketTable.getTableHeader().setBackground(new Color(240, 240, 240));
        ticketTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JScrollPane tableScrollPane = new JScrollPane(ticketTable);
        tableScrollPane.setBorder(new EmptyBorder(20, 0, 0, 0));
        panel.add(tableScrollPane, BorderLayout.CENTER);

        // 刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        refreshButton.setBackground(PRIMARY_COLOR);
        refreshButton.setForeground(Color.WHITE);
        refreshButton.setFocusPainted(false);
        refreshButton.setBorder(new EmptyBorder(8, 20, 8, 20));
        refreshButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        refreshButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                refreshButton.setBackground(new Color(21, 95, 192));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                refreshButton.setBackground(PRIMARY_COLOR);
            }
        });

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBorder(new EmptyBorder(10, 0, 0, 0));
        buttonPanel.add(refreshButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 刷新按钮事件处理
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 清空表格
                tableModel.setRowCount(0);

                List<Ticket> tickets = ticketService.getUserTickets(currentUser.getId());

                if (tickets.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "您还没有购买任何车票。", "我的车票", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    // 添加结果到表格
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    for (Ticket ticket : tickets) {
                        Train train = trainService.getTrainById(ticket.getTrainId());
                        if (train != null) {
                            Object[] row = {
                                    ticket.getId(),
                                    train.getTrainNumber(),
                                    ticket.getSeatNumber(),
                                    train.getDeparture(),
                                    train.getDestination(),
                                    dateFormat.format(train.getDepartureTime()),
                                    ticket.getPrice(),
                                    ticket.isStudentTicket() ? "学生票" : "成人票"
                            };
                            tableModel.addRow(row);
                        }
                    }
                }
            }
        });

        return panel;
    }

    /**
     * 刷新列车表格数据（用于退票后更新余票）
     */
    private void refreshTrainTable(DefaultTableModel tableModel) {
        tableModel.setRowCount(0); // 清空原有数据

        List<Train> trains = trainService.getAllTrains(); // 获取最新数据
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

        for (Train train : trains) {
            Object[] row = {
                    train.getId(),
                    train.getTrainNumber(),
                    train.getDeparture(),
                    train.getDestination(),
                    dateFormat.format(train.getDepartureTime()),
                    dateFormat.format(train.getArrivalTime()),
                    train.getPrice(),
                    train.getAvailableSeats()
            };
            tableModel.addRow(row);
        }
    }


    // 创建退票面板
    private JPanel createCancelTicketPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("退票");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(TEXT_COLOR);
        titleLabel.setBorder(new EmptyBorder(0, 0, 10, 0));
        panel.add(titleLabel, BorderLayout.NORTH);

        // 车票表格
        String[] columnNames = {"票号", "车次", "座位号", "出发站", "到达站", "出发时间", "票价", "票类型", "操作"};




        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 8; // 只有最后一列可编辑
            }
        };



        JTable ticketTable = new JTable(tableModel);
        ticketTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        ticketTable.setRowHeight(30);
        ticketTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
        ticketTable.getTableHeader().setBackground(new Color(240, 240, 240));
        ticketTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        // 设置操作列的渲染器和编辑器
        TableCellRenderer buttonRenderer = (TableCellRenderer) new JButtonRenderer();
        ticketTable.getColumnModel().getColumn(8).setCellRenderer(buttonRenderer);
        ticketTable.getColumnModel().getColumn(8).setCellEditor(
                new DefaultCellEditor(new JCheckBox()) {
                    private JButton button = new JButton("退票");

                    @Override
                    public Component getTableCellEditorComponent(JTable table, Object value,
                                                                 boolean isSelected, int row, int column) {
                        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
                        button.setBackground(Color.RED);
                        button.setForeground(Color.WHITE);
                        button.setFocusPainted(false);
                        button.setBorder(new EmptyBorder(5, 10, 5, 10));

                        // 获取车票ID
                        int ticketId = (int) table.getValueAt(row, 0);

                        button.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                int confirm = JOptionPane.showConfirmDialog(null, "确定要退掉这张车票吗？", "确认退票", JOptionPane.YES_NO_OPTION);
                                if (confirm == JOptionPane.YES_OPTION) {
                                    if (ticketService.cancelTicket(ticketId)) {
                                        JOptionPane.showMessageDialog(null, "退票成功！退款将在3-5个工作日内返还到您的账户。", "退票成功", JOptionPane.INFORMATION_MESSAGE);
                                        refreshTrainTable(tableModel); // 刷新整个表格数据
                                        // 从表格中移除该行
                                        tableModel.removeRow(row);
                                    } else {
                                        JOptionPane.showMessageDialog(null, "退票失败，可能是车票不存在或已退票。", "退票失败", JOptionPane.ERROR_MESSAGE);
                                    }
                                }
                                fireEditingStopped();
                            }
                        });

                        return button;
                    }


                    @Override
                    public Object getCellEditorValue() {
                        return null;
                    }
                }
        );


        JScrollPane tableScrollPane = new JScrollPane(ticketTable);
        tableScrollPane.setBorder(new EmptyBorder(20, 0, 0, 0));
        panel.add(tableScrollPane, BorderLayout.CENTER);

        // 刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        refreshButton.setBackground(PRIMARY_COLOR);
        refreshButton.setForeground(Color.WHITE);
        refreshButton.setFocusPainted(false);
        refreshButton.setBorder(new EmptyBorder(8, 20, 8, 20));
        refreshButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        refreshButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                refreshButton.setBackground(new Color(21, 95, 192));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                refreshButton.setBackground(PRIMARY_COLOR);
            }
        });

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBorder(new EmptyBorder(10, 0, 0, 0));
        buttonPanel.add(refreshButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 刷新按钮事件处理
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 清空表格
                tableModel.setRowCount(0);

                List<Ticket> tickets = ticketService.getUserTickets(currentUser.getId());

                if (tickets.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "您还没有购买任何车票。", "我的车票", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    // 添加结果到表格
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    for (Ticket ticket : tickets) {
                        Train train = trainService.getTrainById(ticket.getTrainId());
                        if (train != null) {
                            Object[] row = {
                                    ticket.getId(),
                                    train.getTrainNumber(),
                                    ticket.getSeatNumber(),
                                    train.getDeparture(),
                                    train.getDestination(),
                                    dateFormat.format(train.getDepartureTime()),
                                    ticket.getPrice(),
                                    ticket.isStudentTicket() ? "学生票" : "成人票",
                                    "退票"
                            };
                            tableModel.addRow(row);
                        }
                    }
                }
            }
        });

        return panel;
    }

    // 创建添加列车面板
    private JPanel createAddTrainPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("添加列车");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(TEXT_COLOR);
        titleLabel.setBorder(new EmptyBorder(0, 0, 10, 0));
        panel.add(titleLabel, BorderLayout.NORTH);

        // 添加列车表单
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                new EmptyBorder(20, 20, 20, 20)
        ));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 10, 5, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 车次
        JLabel trainNumberLabel = new JLabel("车次:");
        trainNumberLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.LINE_START;
        formPanel.add(trainNumberLabel, gbc);

        JTextField trainNumberField = new JTextField(15);
        trainNumberField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 0;
        formPanel.add(trainNumberField, gbc);

        // 出发地
        JLabel departureLabel = new JLabel("出发地:");
        departureLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(departureLabel, gbc);

        JTextField departureField = new JTextField(15);
        departureField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 1;
        formPanel.add(departureField, gbc);

        // 目的地
        JLabel destinationLabel = new JLabel("目的地:");
        destinationLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(destinationLabel, gbc);

        JTextField destinationField = new JTextField(15);
        destinationField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 2;
        formPanel.add(destinationField, gbc);

        // 出发时间
        JLabel departureTimeLabel = new JLabel("出发时间:");
        departureTimeLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(departureTimeLabel, gbc);

        JTextField departureTimeField = new JTextField(15);
        departureTimeField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        departureTimeField.setToolTipText("格式: YYYY-MM-DD HH:mm");
        gbc.gridx = 1;
        gbc.gridy = 3;
        formPanel.add(departureTimeField, gbc);

        // 到达时间
        JLabel arrivalTimeLabel = new JLabel("到达时间:");
        arrivalTimeLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 4;
        formPanel.add(arrivalTimeLabel, gbc);

        JTextField arrivalTimeField = new JTextField(15);
        arrivalTimeField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        arrivalTimeField.setToolTipText("格式: YYYY-MM-DD HH:mm");
        gbc.gridx = 1;
        gbc.gridy = 4;
        formPanel.add(arrivalTimeField, gbc);

        // 总座位数
        JLabel totalSeatsLabel = new JLabel("总座位数:");
        totalSeatsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 5;
        formPanel.add(totalSeatsLabel, gbc);

        JTextField totalSeatsField = new JTextField(15);
        totalSeatsField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 5;
        formPanel.add(totalSeatsField, gbc);

        // 票价
        JLabel priceLabel = new JLabel("票价:");
        priceLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 6;
        formPanel.add(priceLabel, gbc);

        JTextField priceField = new JTextField(15);
        priceField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 6;
        formPanel.add(priceField, gbc);

        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        addButton.setBackground(PRIMARY_COLOR);
        addButton.setForeground(Color.WHITE);
        addButton.setFocusPainted(false);
        addButton.setBorder(new EmptyBorder(8, 20, 8, 20));
        addButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        addButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                addButton.setBackground(new Color(21, 95, 192));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                addButton.setBackground(PRIMARY_COLOR);
            }
        });

        gbc.gridx = 1;
        gbc.gridy = 7;
        gbc.insets = new Insets(15, 10, 5, 10);
        formPanel.add(addButton, gbc);

        panel.add(formPanel, BorderLayout.NORTH);

        // 添加按钮事件处理
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String trainNumber = trainNumberField.getText();
                String departure = departureField.getText();
                String destination = destinationField.getText();
                String departureTimeStr = departureTimeField.getText();
                String arrivalTimeStr = arrivalTimeField.getText();
                String totalSeatsStr = totalSeatsField.getText();
                String priceStr = priceField.getText();

                if (trainNumber.isEmpty() || departure.isEmpty() || destination.isEmpty() ||
                        departureTimeStr.isEmpty() || arrivalTimeStr.isEmpty() ||
                        totalSeatsStr.isEmpty() || priceStr.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "请填写完整的列车信息！", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                Date departureTime = null;
                Date arrivalTime = null;
                try {
                    departureTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(departureTimeStr);
                    arrivalTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(arrivalTimeStr);

                    // 检查出发时间是否早于到达时间
                    if (!departureTime.before(arrivalTime)) {
                        JOptionPane.showMessageDialog(null, "出发时间必须早于到达时间！", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                } catch (ParseException ex) {
                    JOptionPane.showMessageDialog(null, "日期格式错误，请使用 YYYY-MM-DD HH:mm 格式！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                int totalSeats;
                double price;
                try {
                    totalSeats = Integer.parseInt(totalSeatsStr);
                    price = Double.parseDouble(priceStr);
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(null, "座位数和票价必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                Train train = new Train(trainNumber, departure, destination,
                        departureTime, arrivalTime, totalSeats, price);

                if (trainService.addTrain(train)) {
                    JOptionPane.showMessageDialog(null, "添加列车成功！", "成功", JOptionPane.INFORMATION_MESSAGE);

                    // 清空表单
                    trainNumberField.setText("");
                    departureField.setText("");
                    destinationField.setText("");
                    departureTimeField.setText("");
                    arrivalTimeField.setText("");
                    totalSeatsField.setText("");
                    priceField.setText("");
                } else {
                    JOptionPane.showMessageDialog(null, "添加列车失败！", "失败", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        return panel;
    }

    // 创建查看所有列车面板
    private JPanel createViewAllTrainsPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("所有列车");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(TEXT_COLOR);
        titleLabel.setBorder(new EmptyBorder(0, 0, 10, 0));
        panel.add(titleLabel, BorderLayout.NORTH);

        // 列车表格
        String[] columnNames = {"ID", "车次", "出发站", "到达站", "出发时间", "到达时间", "总座位", "余票", "票价"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        JTable trainTable = new JTable(tableModel);
        trainTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        trainTable.setRowHeight(30);
        trainTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
        trainTable.getTableHeader().setBackground(new Color(240, 240, 240));
        trainTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        JScrollPane tableScrollPane = new JScrollPane(trainTable);
        tableScrollPane.setBorder(new EmptyBorder(20, 0, 0, 0));
        panel.add(tableScrollPane, BorderLayout.CENTER);

        // 刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        refreshButton.setBackground(PRIMARY_COLOR);
        refreshButton.setForeground(Color.WHITE);
        refreshButton.setFocusPainted(false);
        refreshButton.setBorder(new EmptyBorder(8, 20, 8, 20));
        refreshButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        // 添加悬停效果
        refreshButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                refreshButton.setBackground(new Color(21, 95, 192));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                refreshButton.setBackground(PRIMARY_COLOR);
            }
        });

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBorder(new EmptyBorder(10, 0, 0, 0));
        buttonPanel.add(refreshButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 刷新按钮事件处理
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 清空表格
                tableModel.setRowCount(0);

                List<Train> trains = trainService.getAllTrains();

                if (trains.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "目前没有列车信息。", "所有列车", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    // 添加结果到表格
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    for (Train train : trains) {
                        Object[] row = {
                                train.getId(),
                                train.getTrainNumber(),
                                train.getDeparture(),
                                train.getDestination(),
                                dateFormat.format(train.getDepartureTime()),
                                dateFormat.format(train.getArrivalTime()),
                                train.getTotalSeats(),
                                train.getAvailableSeats(),
                                train.getPrice()
                        };
                        tableModel.addRow(row);
                    }
                }
            }
        });

        return panel;
    }

    // 导航列表单元格渲染器
    private class NavListCellRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus) {
            Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            if (c instanceof JLabel) {
                JLabel label = (JLabel) c;
                label.setFont(new Font("微软雅黑", Font.PLAIN, 14));
                label.setBorder(new EmptyBorder(10, 20, 10, 0));

                if (isSelected) {
                    label.setBackground(new Color(220, 220, 220));
                    label.setForeground(PRIMARY_COLOR);
                } else {
                    label.setBackground(SECONDARY_COLOR);
                    label.setForeground(TEXT_COLOR);
                }
            }

            return c;
        }
    }

    // 按钮渲染器
    private class JButtonRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus, int row, int column) {
            JButton button = new JButton(value == null ? "" : value.toString());
            button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
            button.setForeground(Color.WHITE);
            button.setFocusPainted(false);
            button.setBorder(new EmptyBorder(5, 10, 5, 10));

            if (column == 8) { // 操作列
                if (table.getName() != null && table.getName().equals("ticketTable")) {
                    button.setBackground(Color.RED); // 退票按钮
                } else {
                    button.setBackground(ACCENT_COLOR); // 购票按钮
                }
            }

            return button;
        }
    }

    // 验证手机号是否合法
    private static boolean isValidMobileNo(String mobileNo) {
        return mobileNo.matches("^1\\d{10}$");
    }

    // 验证身份证号是否合法
    private static boolean isValidIdCardNo(String idCardNo) {
        return idCardNo.matches("^\\d{18}$");
    }

    // 验证银行卡号是否合法
    private static boolean isValidBankCardNo(String bankCardNo) {
        return bankCardNo.matches("^\\d{19}$");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                MainGUI gui = new MainGUI();
                gui.setVisible(true);
            }
        });
    }
}